# -*- coding: utf-8 -*-

import logging
import hashlib
import string
import json

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from fidoweb.lib.base import Session, BaseController, render
from fidoweb.lib.formChecker import FormChecker
from fidoweb.model.school import *
from fidoweb.model.user import *
from fidoweb.controllers.login import LoginController
from fidoweb.controllers.userGroup import UserGroupController

log = logging.getLogger(__name__)

"""
Authority:
	Name			UserGroupName											Method
	UserInserting	Operation.HumanResource.UserManagement.UserInserting	insertUser
						
"""

class OaController(BaseController) :
	_authority = {
		'UserInserting' : 'Operation.HumanResource.UserManagement.Inserting'
	}
	
	def insertUser(self) :
		if (not self._haveAuthority('UserInserting')) : return 'no authority'
		fc = FormChecker()
		if (not ('fidocard' in request.POST) or not fc.isValidFidocard(request.POST['fidocard'])) : return 'fidocard error'
		if (not ('mobile' in request.POST) or not fc.isValidMobile(request.POST['mobile'])) : return 'mobile error'
		if (not ('name' in request.POST) or not fc.isValidName(request.POST['name'])) : return 'name error'
		if (not ('gender' in request.POST) or (request.POST['gender'] != 'male' and request.POST['gender'] != 'female')) : return 'gender error'
		if (not ('birthday' in request.POST) or (fc.strToDate(request.POST['birthday']) == None)) : return 'birthday error'
		if (not ('email' in request.POST) or not fc.isValidEmail(request.POST['email'])) : return 'email error'
		if (not ('school' in request.POST)) : return 'school error'
		else : 
			try :
				school = int(request.POST['school'])
			except :
				return 'school error'
		if (not ('profession' in request.POST)) : return 'profession error'
		else : 
			try :
				profession = int(request.POST['profession'])
			except :
				return 'profession error'
		if (not ('grade' in request.POST)) : return 'grade error'
		else :
			try :
				grade = int(request.POST['grade'])
			except :
				return 'grade error'
		if (grade < 1900 or grade > datetime.datetime.today().year) : return 'grade error'
		if (Session.query(School).filter_by(id = school).count() == 0) : return 'school error'
		if (Session.query(Profession).filter_by(id = profession).count() == 0) : return 'profession error'
		if (Session.query(User).filter_by(mobile = request.POST['mobile']).count() > 0) : return 'mobile registered'
		if (Session.query(User).filter_by(fidocard = request.POST['fidocard']).count() > 0) : return 'fidocard registered'
		if (Session.query(User).filter_by(email = request.POST['email']).count() > 0) : return 'email registered'
		password = hashlib.sha512(request.POST['mobile']).hexdigest()
		user = User(name = request.POST['name'], password = password, gender = request.POST['gender'], 
			mobile = request.POST['mobile'], birthday = fc.strToDate(request.POST['birthday']), email = request.POST['email'],
			fidocard = request.POST['fidocard'])
		Session.add(user)
		Session.commit()
		user_school = School_User(user_id = user.id, school_id = school, profession_id = profession, grade = grade)
		Session.add(user_school)
		Session.commit()
		return 'success'
	
	def index(self) :
		lc = LoginController()
		user = lc._getLoginUser()
		c.title = 'OA'
		c.header = render('/oa/header.mako')
		if (user == None) :
			c.content = '请登录。'.decode("utf8")
		else :
			oaUsers = Session.query(OAUser).filter_by(id = user.id)
			if (oaUsers.count() == 0) :
				c.content = '抱歉，您的账号没有开通OA。'.decode("utf8")
			else :
				c.content = render('/oa/content.mako')
		return render('global/global.mako')
	
	def _haveAuthority(self, authName) :
		uc = UserGroupController()
		lc = LoginController()
		user = lc._getLoginUser()
		if (user == None) : return False
		return uc._inGroup(user, Session.query(UserGroup).filter_by(name = self._authority[authName]).first())
	
	def getPage(self) :
		if (not ('authName' in request.POST)) : return ''
		authName = request.POST['authName']
		if (self._haveAuthority(authName)) :
			return render('/oa/page_' + string.lower(authName) + '.mako')
		else :
			return '抱歉，您没有访问此功能的权限。'.decode("utf8")
	
	def getTaskList(self) :
		"""
			Return Format:
				JSON List: 
					[ [Desctiption: String, Entry: String], ... ]
		"""
		response.headers['Content-Type'] = 'application/x-json'
		ret = list()
		if (self._haveAuthority('UserInserting')) : ret.append(['用户录入'.decode('utf8'), 'UserInserting'])
		return json.dumps(ret)
	
	def _getOAUserId(self) :
		lc = LoginController()
		user = lc._getLoginUser()
		if (user == None) : return None
		oaUsers = Session.query(OAUser).filter_by(id = user.id)
		if (oaUsers.count() == 0) : return None
		return user.id